package io.p2p.stream.turn.handler.udp;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.turn.handler.TurnBaseHandler;
import io.p2p.stream.turn.node.ActiveNode;
import io.p2p.stream.turn.session.ActiveNodeSessionManager;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

@Slf4j
public class DataRelayHandler implements TurnBaseHandler {

    public static final String commandType = "dataRelay";

    @Override
    public void process(ChannelHandlerContext ctx, InetSocketAddress remoteAddress, String buffer) {

    }

    @Override
    public void process(ChannelHandlerContext ctx, InetSocketAddress remoteAddress, JSONObject buffer) {
        String toName = buffer.getString("to");

        ActiveNode toActiveNode = ActiveNodeSessionManager.getInstance().find(toName);

        if(toActiveNode == null){
            return;
        }

        log.info("Relay Message: {}",buffer.toJSONString());

        buffer.put("type","dataRelayAck");
        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                buffer.toJSONString(), StandardCharsets.UTF_8), new InetSocketAddress(toActiveNode.getIp(),toActiveNode.getPort())));
    }

    @Override
    public void process(ChannelHandlerContext ctx, InetSocketAddress remoteAddress, Byte[] buffer) {

    }
}
